/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufg.inf.si.poo.formula1.GUI;

import br.ufg.inf.si.poo.formula1.Circuit.Circuit;
import br.ufg.inf.si.poo.formula1.Interface.InterfaceRegister;
import br.ufg.inf.si.poo.formula1.Library.Library;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFiles;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFilesRace;
import br.ufg.inf.si.poo.formula1.ManagementFiles.ManagementFilesSeason;
import br.ufg.inf.si.poo.formula1.Race.Race;
import br.ufg.inf.si.poo.formula1.Simulator.SimulatorGridRace;
import br.ufg.inf.si.poo.formula1.Simulator.SimulatorQualification;
import br.ufg.inf.si.poo.formula1.Simulator.SimulatorRace;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JOptionPane;


    /**
 * FrameDefault
 *
 * Versao 1.0
 *
 * Data 16/02/2013
 *
 * @author Igor
 */
public class ManageRaceSeason extends javax.swing.JInternalFrame implements InterfaceRegister {
    //Atributos
    private Circuit circuit;
    private Race race;
    private Boolean emEdicao; //Valida se esta em modo de edicao ou nao
    /**
     * Creates new form FrameDefault
     */
    public ManageRaceSeason() {
        initComponents();
        clearFields();
    }

    /**
     * Exibe os pilotos vinculados no JList de pilotos vinculados
     */
    private void driversLinkedList(){
        this.labelQtdPilotosVinculados.setText("Pilotos: 0 de 26");
        if(this.race != null){
            String[] drivers = new String[26]; //Maximo de 20 circuitos por temporada
            //Lista Pilotos Vinculados
            for(int i = 0;i < this.race.getQttDrivers();i++){
                if(this.race.getDrivers()[i] != null){
                    drivers[i] = Library.setLengthString(this.race.getDrivers()[i].getDriverName(),15);
                }
            }
            this.labelQtdPilotosVinculados.setText("Pilotos: "+this.race.getQttDrivers()+" de 26");
            this.listPilotosVinculados.setListData(drivers);
        }
    }

    private void checkQttDriversInSeason() throws IllegalStateException{
        if(FrameMain.getSeasonLoaded().getQttDriver() < 18){
            throw new IllegalStateException("Quantidade de pilotos na temporada inferior ao permitido:"+
                    "\nPermitido: igual ou maior que 18 \tQuantidade atual: "+FrameMain.getSeasonLoaded().getQttDriver());
        }
    }

    /**
     * Vincular pilotos para corrida selecionada
     */
    private void linkDriversRace() throws IllegalArgumentException{
        if(this.race != null){
            try{
                checkFields();
                checkValueEntered();
                checkQttDriversInSeason();
                this.race.validateStatus(1); //Codigo 1 referente aa vinculacao de pilotos
                SimulatorRace.selectsDriversToRace(FrameMain.getSeasonLoaded(), this.race);
                this.race.setStatus(3); //3 quer dizer que a corrida esta pronta para acontecer
                createObject();
                dataShowObject();
            }catch (IllegalArgumentException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }catch (ParseException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }catch (IllegalStateException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Erro", JOptionPane.ERROR_MESSAGE);
                throw new IllegalStateException();
            }
        }else{
            JOptionPane.showMessageDialog(this, "Selecione um circuito.", "Erro!", JOptionPane.ERROR_MESSAGE);
            throw new IllegalArgumentException();
        }
    }

    /**
     * Simula qualificacao da corrida selecionada
     */
    private void simulateQualification() throws IllegalArgumentException{
        if (this.race != null) {
            try{
                checkFields();
                checkValueEntered();
                this.race.validateStatus(3); //Codigo 3 referente aa execucao da qualificacao
                this.race.setQualification();
                SimulatorQualification.exercuteQualification(this.race.getQualification());
                ManagementFilesRace.writeQualificationRace(this.race, FrameMain.getFolderSeasonLoaded());
                this.race.setStatus(4);
                createObject();
                dataShowObject();
            }catch(IllegalArgumentException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }catch (ParseException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }
        }else{
            JOptionPane.showMessageDialog(this, "Selecione um circuito.", "Erro!", JOptionPane.ERROR_MESSAGE);
            throw new IllegalArgumentException();
        }
    }

    /**
     * Simula a corrida corrida
     */
    private void simulateRace() throws IllegalArgumentException{
        if (this.race != null) {
            try{
                checkFields();
                checkValueEntered();
                this.race.validateStatus(2); //Codigo 3 referente aa execucao da qualificacao
                this.race.setGridRace(this.race.getQualification());
                SimulatorGridRace.generateTimes(this.race);
                ManagementFilesRace.writeGridRaceRce(this.race, FrameMain.getFolderSeasonLoaded());
                this.race.setStatus(2);
                createObject();
                ManagementFilesSeason.writeTeamSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
                ManagementFilesSeason.writeHireDriverSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());                
                simulateWorldChampionship();
                dataShowObject();
            }catch(IllegalArgumentException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }catch (ParseException e){
                JOptionPane.showMessageDialog(this, e.getMessage(), "Atençao", JOptionPane.WARNING_MESSAGE);
                throw new IllegalArgumentException();
            }
        }else{
            JOptionPane.showMessageDialog(this, "Selecione um circuito.", "Erro!", JOptionPane.ERROR_MESSAGE);
            throw new IllegalArgumentException();
        }
    }

    /**
     * Simula os campeonatos mundial de piloto e construtor caso todas as corridas tenham sido realizadas
     */
    private void simulateWorldChampionship(){
        Boolean finishSeason = true;
        for(int i = 0;i < FrameMain.getSeasonLoaded().getQttCircuits();i++){
            Race race1 = FrameMain.getSeasonLoaded().getRace()[i];
            if(race1 != null){
                if(race1.getStatus() != 1 && race1.getStatus() != 2){
                    finishSeason = false;
                }
            }
        }
        if(finishSeason){
            /* Campeao mundial */
            FrameMain.getSeasonLoaded().worldChampion();

            /* Campeonato mundial de contrutores */
            FrameMain.getSeasonLoaded().worldChampionshipBuilders();
            
            ManagementFilesSeason.writeWorldChampionshipDrivers(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.writeWorldChampionshipBuilders(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelTitulo = new javax.swing.JPanel();
        labelTitulo = new javax.swing.JLabel();
        panelDadosPrincipais = new javax.swing.JPanel();
        panelCircuitosCadastrados = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listCircuitos = new javax.swing.JList();
        pageControlDadosCorridas = new javax.swing.JTabbedPane();
        tabPanelInfirmacoes = new javax.swing.JPanel();
        labelPais = new javax.swing.JLabel();
        labelPais1 = new javax.swing.JLabel();
        labelCidade1 = new javax.swing.JLabel();
        labelCidade = new javax.swing.JLabel();
        LabelData = new javax.swing.JLabel();
        textData = new javax.swing.JTextField();
        labelNome1 = new javax.swing.JLabel();
        labelNome = new javax.swing.JLabel();
        labelNumeroVoltas = new javax.swing.JLabel();
        labelNumeroVoltas1 = new javax.swing.JLabel();
        labelDistanciaVolta1 = new javax.swing.JLabel();
        labelDistanciaVolta = new javax.swing.JLabel();
        labelTamanho1 = new javax.swing.JLabel();
        labelTamanho = new javax.swing.JLabel();
        labelPrimeiroGrandPrix = new javax.swing.JLabel();
        labelPrimeiroGrandPrix1 = new javax.swing.JLabel();
        labelVoltaRecord1 = new javax.swing.JLabel();
        labelVoltaRecord = new javax.swing.JLabel();
        labelStatus = new javax.swing.JLabel();
        labelStatus1 = new javax.swing.JLabel();
        buttonSimularQualificacaoMaisCorrida = new javax.swing.JButton();
        tabPanelPilotos = new javax.swing.JPanel();
        buttonVincularPilotos = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        listPilotosVinculados = new javax.swing.JList();
        labelQtdPilotosVinculados = new javax.swing.JLabel();
        tabPanelSimularQualificacao = new javax.swing.JPanel();
        buttonSimularQualificacao = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        tableQualification = new javax.swing.JTable();
        tabpanelSimularCorrida = new javax.swing.JPanel();
        buttonSimularCorrida = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        tableRace = new javax.swing.JTable();
        panelBotoes = new javax.swing.JPanel();
        buttonSalvar = new javax.swing.JButton();
        labelCamposObrigatorios = new javax.swing.JLabel();
        buttonNovo = new javax.swing.JButton();
        buttonSimularTodasCorridas = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Gerenciar Corridas da Temporada");
        setPreferredSize(new java.awt.Dimension(800, 600));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        panelTitulo.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        labelTitulo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        labelTitulo.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        labelTitulo.setText("Tela utilizada para gerenciar as corridas da temporada");

        javax.swing.GroupLayout panelTituloLayout = new javax.swing.GroupLayout(panelTitulo);
        panelTitulo.setLayout(panelTituloLayout);
        panelTituloLayout.setHorizontalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelTitulo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        panelTituloLayout.setVerticalGroup(
            panelTituloLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelTituloLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelTitulo)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        panelDadosPrincipais.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Dados Principais   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        panelCircuitosCadastrados.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "   Circuitos   ", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 10), java.awt.Color.black)); // NOI18N

        listCircuitos.setToolTipText("Lista de circuitos cadastrados");
        listCircuitos.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                listCircuitosValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(listCircuitos);

        javax.swing.GroupLayout panelCircuitosCadastradosLayout = new javax.swing.GroupLayout(panelCircuitosCadastrados);
        panelCircuitosCadastrados.setLayout(panelCircuitosCadastradosLayout);
        panelCircuitosCadastradosLayout.setHorizontalGroup(
            panelCircuitosCadastradosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
        );
        panelCircuitosCadastradosLayout.setVerticalGroup(
            panelCircuitosCadastradosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );

        labelPais.setText("País:");

        labelPais1.setText("Valores");

        labelCidade1.setText("Valores");

        labelCidade.setText("Cidade:");

        LabelData.setText("Data da Corrida:");

        labelNome1.setText("Valores");

        labelNome.setText("Nome:");

        labelNumeroVoltas.setText("Número de Voltas:");

        labelNumeroVoltas1.setText("Valores");

        labelDistanciaVolta1.setText("Valores");

        labelDistanciaVolta.setText("Distância da Volta (KM):");

        labelTamanho1.setText("Valores");

        labelTamanho.setText("Tamanho (KM):");

        labelPrimeiroGrandPrix.setText("Primeiro Grand Prix:");

        labelPrimeiroGrandPrix1.setText("Valores");

        labelVoltaRecord1.setText("Valores");

        labelVoltaRecord.setText("Volta recorde:");

        labelStatus.setText("Status:");

        labelStatus1.setText("Status:");

        buttonSimularQualificacaoMaisCorrida.setText("Simular Qualificação e Corrida");
        buttonSimularQualificacaoMaisCorrida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSimularQualificacaoMaisCorridaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout tabPanelInfirmacoesLayout = new javax.swing.GroupLayout(tabPanelInfirmacoes);
        tabPanelInfirmacoes.setLayout(tabPanelInfirmacoesLayout);
        tabPanelInfirmacoesLayout.setHorizontalGroup(
            tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabPanelInfirmacoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(buttonSimularQualificacaoMaisCorrida)
                    .addComponent(labelStatus)
                    .addComponent(labelVoltaRecord)
                    .addComponent(labelPrimeiroGrandPrix)
                    .addComponent(labelTamanho)
                    .addComponent(labelDistanciaVolta)
                    .addComponent(labelNumeroVoltas)
                    .addComponent(labelNome)
                    .addComponent(LabelData)
                    .addComponent(labelCidade)
                    .addComponent(labelPais))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(labelStatus1)
                    .addComponent(labelVoltaRecord1)
                    .addComponent(labelPrimeiroGrandPrix1)
                    .addComponent(labelTamanho1)
                    .addComponent(labelDistanciaVolta1)
                    .addComponent(labelNumeroVoltas1)
                    .addComponent(labelNome1)
                    .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelCidade1)
                    .addComponent(labelPais1))
                .addContainerGap(276, Short.MAX_VALUE))
        );
        tabPanelInfirmacoesLayout.setVerticalGroup(
            tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabPanelInfirmacoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelPais)
                    .addComponent(labelPais1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelCidade)
                    .addComponent(labelCidade1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(LabelData)
                    .addComponent(textData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelNome)
                    .addComponent(labelNome1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelNumeroVoltas)
                    .addComponent(labelNumeroVoltas1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelDistanciaVolta)
                    .addComponent(labelDistanciaVolta1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelTamanho)
                    .addComponent(labelTamanho1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelPrimeiroGrandPrix)
                    .addComponent(labelPrimeiroGrandPrix1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelVoltaRecord)
                    .addComponent(labelVoltaRecord1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabPanelInfirmacoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(labelStatus1)
                    .addComponent(labelStatus))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonSimularQualificacaoMaisCorrida)
                .addContainerGap(89, Short.MAX_VALUE))
        );

        pageControlDadosCorridas.addTab("Informações", tabPanelInfirmacoes);

        buttonVincularPilotos.setText("Vincular Pilotos");
        buttonVincularPilotos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonVincularPilotosActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(listPilotosVinculados);

        labelQtdPilotosVinculados.setText("Quantidade de Pilotos Vinculados");

        javax.swing.GroupLayout tabPanelPilotosLayout = new javax.swing.GroupLayout(tabPanelPilotos);
        tabPanelPilotos.setLayout(tabPanelPilotosLayout);
        tabPanelPilotosLayout.setHorizontalGroup(
            tabPanelPilotosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
            .addGroup(tabPanelPilotosLayout.createSequentialGroup()
                .addComponent(labelQtdPilotosVinculados)
                .addGap(0, 0, Short.MAX_VALUE))
            .addComponent(buttonVincularPilotos, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        tabPanelPilotosLayout.setVerticalGroup(
            tabPanelPilotosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabPanelPilotosLayout.createSequentialGroup()
                .addComponent(labelQtdPilotosVinculados)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonVincularPilotos, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pageControlDadosCorridas.addTab("Vicular Pilotos", tabPanelPilotos);

        buttonSimularQualificacao.setText("Simular Qualificação");
        buttonSimularQualificacao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSimularQualificacaoActionPerformed(evt);
            }
        });

        tableQualification.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Pos", "No", "Driver", "Team", "Q1", "Q2", "Q3", "Laps"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableQualification.getTableHeader().setReorderingAllowed(false);
        jScrollPane4.setViewportView(tableQualification);
        tableQualification.getColumnModel().getColumn(0).setResizable(false);
        tableQualification.getColumnModel().getColumn(0).setPreferredWidth(100);
        tableQualification.getColumnModel().getColumn(1).setResizable(false);
        tableQualification.getColumnModel().getColumn(1).setPreferredWidth(50);
        tableQualification.getColumnModel().getColumn(2).setResizable(false);
        tableQualification.getColumnModel().getColumn(2).setPreferredWidth(200);
        tableQualification.getColumnModel().getColumn(3).setResizable(false);
        tableQualification.getColumnModel().getColumn(3).setPreferredWidth(200);
        tableQualification.getColumnModel().getColumn(4).setResizable(false);
        tableQualification.getColumnModel().getColumn(4).setPreferredWidth(100);
        tableQualification.getColumnModel().getColumn(5).setResizable(false);
        tableQualification.getColumnModel().getColumn(5).setPreferredWidth(100);
        tableQualification.getColumnModel().getColumn(6).setResizable(false);
        tableQualification.getColumnModel().getColumn(6).setPreferredWidth(100);
        tableQualification.getColumnModel().getColumn(7).setResizable(false);
        tableQualification.getColumnModel().getColumn(7).setPreferredWidth(60);

        javax.swing.GroupLayout tabPanelSimularQualificacaoLayout = new javax.swing.GroupLayout(tabPanelSimularQualificacao);
        tabPanelSimularQualificacao.setLayout(tabPanelSimularQualificacaoLayout);
        tabPanelSimularQualificacaoLayout.setHorizontalGroup(
            tabPanelSimularQualificacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
            .addComponent(buttonSimularQualificacao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        tabPanelSimularQualificacaoLayout.setVerticalGroup(
            tabPanelSimularQualificacaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabPanelSimularQualificacaoLayout.createSequentialGroup()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSimularQualificacao))
        );

        pageControlDadosCorridas.addTab("Simular Qualificação", tabPanelSimularQualificacao);

        buttonSimularCorrida.setText("Simular Corrida");
        buttonSimularCorrida.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSimularCorridaActionPerformed(evt);
            }
        });

        tableRace.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Pos", "No", "Driver", "Team", "Laps", "Time/Retired", "Grid", "Pts"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableRace.getTableHeader().setReorderingAllowed(false);
        jScrollPane5.setViewportView(tableRace);
        tableRace.getColumnModel().getColumn(0).setResizable(false);
        tableRace.getColumnModel().getColumn(0).setPreferredWidth(100);
        tableRace.getColumnModel().getColumn(1).setResizable(false);
        tableRace.getColumnModel().getColumn(1).setPreferredWidth(50);
        tableRace.getColumnModel().getColumn(2).setResizable(false);
        tableRace.getColumnModel().getColumn(2).setPreferredWidth(200);
        tableRace.getColumnModel().getColumn(3).setResizable(false);
        tableRace.getColumnModel().getColumn(3).setPreferredWidth(200);
        tableRace.getColumnModel().getColumn(4).setResizable(false);
        tableRace.getColumnModel().getColumn(4).setPreferredWidth(60);
        tableRace.getColumnModel().getColumn(5).setResizable(false);
        tableRace.getColumnModel().getColumn(5).setPreferredWidth(200);
        tableRace.getColumnModel().getColumn(6).setResizable(false);
        tableRace.getColumnModel().getColumn(6).setPreferredWidth(50);
        tableRace.getColumnModel().getColumn(7).setResizable(false);
        tableRace.getColumnModel().getColumn(7).setPreferredWidth(50);

        javax.swing.GroupLayout tabpanelSimularCorridaLayout = new javax.swing.GroupLayout(tabpanelSimularCorrida);
        tabpanelSimularCorrida.setLayout(tabpanelSimularCorridaLayout);
        tabpanelSimularCorridaLayout.setHorizontalGroup(
            tabpanelSimularCorridaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
            .addComponent(buttonSimularCorrida, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        tabpanelSimularCorridaLayout.setVerticalGroup(
            tabpanelSimularCorridaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, tabpanelSimularCorridaLayout.createSequentialGroup()
                .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSimularCorrida))
        );

        pageControlDadosCorridas.addTab("Simular Corrida", tabpanelSimularCorrida);

        javax.swing.GroupLayout panelDadosPrincipaisLayout = new javax.swing.GroupLayout(panelDadosPrincipais);
        panelDadosPrincipais.setLayout(panelDadosPrincipaisLayout);
        panelDadosPrincipaisLayout.setHorizontalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(pageControlDadosCorridas, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelCircuitosCadastrados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        panelDadosPrincipaisLayout.setVerticalGroup(
            panelDadosPrincipaisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(panelCircuitosCadastrados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(panelDadosPrincipaisLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pageControlDadosCorridas, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
        );

        panelBotoes.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        buttonSalvar.setText("Salvar");
        buttonSalvar.setToolTipText("Clique para salvar os dados digitados");
        buttonSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSalvarActionPerformed(evt);
            }
        });

        labelCamposObrigatorios.setText("Campos marcados com *, são obrigatórios");

        buttonNovo.setText("Atualizar");
        buttonNovo.setToolTipText("Clique para cadastrar um novo registro");
        buttonNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNovoActionPerformed(evt);
            }
        });

        buttonSimularTodasCorridas.setText("Simular Todas Corridas");
        buttonSimularTodasCorridas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSimularTodasCorridasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelBotoesLayout = new javax.swing.GroupLayout(panelBotoes);
        panelBotoes.setLayout(panelBotoesLayout);
        panelBotoesLayout.setHorizontalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelCamposObrigatorios)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(buttonSimularTodasCorridas)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonNovo)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonSalvar)
                .addContainerGap())
        );

        panelBotoesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {buttonNovo, buttonSalvar});

        panelBotoesLayout.setVerticalGroup(
            panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotoesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSalvar)
                    .addComponent(labelCamposObrigatorios)
                    .addComponent(buttonNovo)
                    .addComponent(buttonSimularTodasCorridas))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelTitulo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(panelBotoes, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(panelTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelDadosPrincipais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void listCircuitosValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_listCircuitosValueChanged
        // TODO add your handling code here:
        if(this.listCircuitos.getSelectedIndex() != -1){
            Circuit circuit1 = Library.returnCircuit( (String)this.listCircuitos.getSelectedValue());
            if(circuit1 != null){
                this.race = Library.returnRace(circuit1.getCountry());
                this.circuit = circuit1;
                this.emEdicao = true;
            }
        }
        dataShowObject();
    }//GEN-LAST:event_listCircuitosValueChanged

    private void buttonSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSalvarActionPerformed
        // TODO add your handling code here:
        // TODO add your handling code here:
        try{
            checkFields();

            checkValueEntered();

            createObject();

            clearFields();
        }catch(IllegalArgumentException e){
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
        }catch(ParseException e){
            JOptionPane.showMessageDialog(this, e.getMessage(), "Erro!", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_buttonSalvarActionPerformed

    private void buttonNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonNovoActionPerformed
        // TODO add your handling code here:
        clearFields();
    }//GEN-LAST:event_buttonNovoActionPerformed

    private void buttonVincularPilotosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonVincularPilotosActionPerformed
        // TODO add your handling code here:
        linkDriversRace();
    }//GEN-LAST:event_buttonVincularPilotosActionPerformed

    private void buttonSimularQualificacaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSimularQualificacaoActionPerformed
        // TODO add your handling code here:
        simulateQualification();
    }//GEN-LAST:event_buttonSimularQualificacaoActionPerformed

    private void buttonSimularCorridaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSimularCorridaActionPerformed
        // TODO add your handling code here:
        simulateRace();
    }//GEN-LAST:event_buttonSimularCorridaActionPerformed

    private void buttonSimularQualificacaoMaisCorridaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSimularQualificacaoMaisCorridaActionPerformed
        // TODO add your handling code here:
        try{
            linkDriversRace();
            simulateQualification();
            simulateRace();
        }catch(IllegalArgumentException e){
            //Nao eh necessario validar, pois a validacao ja esta sendo feita dentro dos metodos
        }catch (IllegalStateException e) {
            //Nao eh necessario validar, pois a validacao ja esta sendo feita dentro dos metodos
        }
    }//GEN-LAST:event_buttonSimularQualificacaoMaisCorridaActionPerformed

    private void buttonSimularTodasCorridasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSimularTodasCorridasActionPerformed
        // TODO add your handling code here:
        try {
            for (int i = 0; i < FrameMain.getSeasonLoaded().getQttCircuits(); i++) {
                Circuit circuit1 = FrameMain.getSeasonLoaded().getCircuits()[i];
                this.emEdicao = false;
                if (circuit1 != null) {
                    Race race1 = FrameMain.getSeasonLoaded().getRace()[i];
                    if (race1 != null) {
                        this.race = race1;
                        this.circuit = circuit1;
                        this.emEdicao = true;
                        if (this.race.getStatus() == 0) {
                            linkDriversRace();
                        }
                        if (this.race.getStatus() == 3) {
                            simulateQualification();
                        }
                        if (this.race.getStatus() == 4) {
                            simulateRace();
                        }
                    }
                }
            }
        } catch (IllegalArgumentException e) {
            //Nao eh necessario validar, pois a validacao ja esta sendo feita dentro dos metodos
        }catch (IllegalStateException e) {
            //Nao eh necessario validar, pois a validacao ja esta sendo feita dentro dos metodos
        }
    }//GEN-LAST:event_buttonSimularTodasCorridasActionPerformed

    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        clearFields();
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel LabelData;
    private javax.swing.JButton buttonNovo;
    private javax.swing.JButton buttonSalvar;
    private javax.swing.JButton buttonSimularCorrida;
    private javax.swing.JButton buttonSimularQualificacao;
    private javax.swing.JButton buttonSimularQualificacaoMaisCorrida;
    private javax.swing.JButton buttonSimularTodasCorridas;
    private javax.swing.JButton buttonVincularPilotos;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JLabel labelCamposObrigatorios;
    private javax.swing.JLabel labelCidade;
    private javax.swing.JLabel labelCidade1;
    private javax.swing.JLabel labelDistanciaVolta;
    private javax.swing.JLabel labelDistanciaVolta1;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelNome1;
    private javax.swing.JLabel labelNumeroVoltas;
    private javax.swing.JLabel labelNumeroVoltas1;
    private javax.swing.JLabel labelPais;
    private javax.swing.JLabel labelPais1;
    private javax.swing.JLabel labelPrimeiroGrandPrix;
    private javax.swing.JLabel labelPrimeiroGrandPrix1;
    private javax.swing.JLabel labelQtdPilotosVinculados;
    private javax.swing.JLabel labelStatus;
    private javax.swing.JLabel labelStatus1;
    private javax.swing.JLabel labelTamanho;
    private javax.swing.JLabel labelTamanho1;
    private javax.swing.JLabel labelTitulo;
    private javax.swing.JLabel labelVoltaRecord;
    private javax.swing.JLabel labelVoltaRecord1;
    private javax.swing.JList listCircuitos;
    private javax.swing.JList listPilotosVinculados;
    private javax.swing.JTabbedPane pageControlDadosCorridas;
    private javax.swing.JPanel panelBotoes;
    private javax.swing.JPanel panelCircuitosCadastrados;
    private javax.swing.JPanel panelDadosPrincipais;
    private javax.swing.JPanel panelTitulo;
    private javax.swing.JPanel tabPanelInfirmacoes;
    private javax.swing.JPanel tabPanelPilotos;
    private javax.swing.JPanel tabPanelSimularQualificacao;
    private javax.swing.JTable tableQualification;
    private javax.swing.JTable tableRace;
    private javax.swing.JPanel tabpanelSimularCorrida;
    private javax.swing.JTextField textData;
    // End of variables declaration//GEN-END:variables

    @Override
    public void dataShowObject() {
        this.labelPais1.setText(this.circuit.getCountry());
        this.labelCidade1.setText(this.circuit.getCity());

        this.textData.setText(this.circuit.getRaceDate());

        this.labelNome1.setText(this.circuit.getCircuitName());
        this.labelNumeroVoltas1.setText(""+this.circuit.getNumberLaps());
        this.labelDistanciaVolta1.setText(""+this.circuit.getCircuitLength());
        this.labelTamanho1.setText(""+this.circuit.getRaceDistance());
        this.labelPrimeiroGrandPrix1.setText(""+this.circuit.getFirstGrandPrix());
        this.labelVoltaRecord1.setText(Library.convertMilliseconds(this.circuit.getLapRecordTime(),"MINUTOS")+" - "+this.circuit.getLapRecordDriver());
        if(this.race != null){
            switch(this.race.getStatus()){
                case 0: 
                    this.labelStatus1.setText("Corrida sem pilotos vinculados");
                    break;
                case 1:
                    this.labelStatus1.setText("A corrida não foi realizada devido à falta de pilotos");
                    break;
                case 2:
                    this.labelStatus1.setText("Corrida já foi realizada");
                    break;
                case 3:
                    this.labelStatus1.setText("Qualificação já pode ser realizada");
                    break;
                case 4:
                    this.labelStatus1.setText("Corrida já pode ser realizada");
                    break;
                default:
                    this.labelStatus1.setText("Status não avaliado");
            }
        }else{
            this.labelStatus1.setText("");
        }

        driversLinkedList();
        Library.insertLinesTableQualification(this.tableQualification, this.race);
        Library.insertLinesTableRace(this.tableRace, this.race);
    }

    @Override
    public void checkFields() throws IllegalArgumentException {
        String texto = "Campos obrigatórios estão vazios.";
        if(this.textData.getText().equals("")) {
            throw new IllegalArgumentException(texto + "\nDigite um valor válido para Data.");
        }
    }

    @Override
    public void checkValueEntered() throws IllegalArgumentException, ParseException {
        //Data
        //DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");  
        try{
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            Date data = (java.util.Date) formatter.parse(this.textData.getText());
        }catch(ParseException e){
            throw new ParseException("Valor inválido de Data.", 0);
        }
    }

    @Override
    public void createObject() throws IllegalArgumentException {
        //Se nao estiver em modo de edicao entao adiciona, pois eh um novo Objeto, caso contrario apenas alterara
        if (this.emEdicao) {
            this.circuit.setRaceDate(this.textData.getText());
            ManagementFilesSeason.writeCircuitSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            ManagementFilesSeason.createRaceSeason(FrameMain.getSeasonLoaded());
            ManagementFilesSeason.writeRaceSeason(FrameMain.getSeasonLoaded(), FrameMain.getFolderSeasonLoaded());
            //Atualiza os dados atualizados do piloto
            ManagementFiles.writeDriver(FrameMain.getDrivers());
            //Atualiza a volta recorde
            ManagementFiles.writeCircuit(FrameMain.getCircuits());
        }
    }

    @Override
    public void clearFields() {
        this.circuit = new Circuit();
        this.race = null;
        this.emEdicao = false;

        this.listCircuitos.setSelectedIndex(0);

        dataShowObject();
        this.labelTitulo.setText("Tela utilizada para gerenciar as equipes da temporada de "+FrameMain.getSeasonLoaded().getYear());
        Library.indexedListCircuits(this.listCircuitos, null, FrameMain.getSeasonLoaded());
    }
}
